<template>
  <view class="content">
    <view class="header">
	 <div style="flex: 1;">
		 <!-- <u-search
			  placeholder="请输入查询" 
			  @clear="clearSearch" 
			  @change='searchChange'
			  :show-action='false' 
			  v-model="searchValue" 
			  shape="round" 
			  clearabled>
		 </u-search> -->
		 <u-search v-model="requestParams.deviceModel" placeholder="请输入设备型号进行搜索" :clearabled="true"
		 	:showAction="false"></u-search>
	 </div>
	  <div>
		  <u-button
				type="primary" 
				size="mini" 
				text="新增设备" 
				@click="handleAddDevice" 
				>
		  </u-button>
	  </div>
    </view>
    <view class="main">
      <view class="main_body" v-for="(item, index) in list" :key="index">
        <view class="detail">
          <view class="main_content">
            <view class="main_body_view">
              设备类型：{{ item.name}}
            </view>
          </view>
        </view>
		<view class="button" style="margin-bottom: 10px;">
			<u-button type="primary" size="mini" @click="handleConfirm(item)">确定</u-button>
		</view>
		<view class="footer" />
      </view>
    </view>
	<!-- 新增设备类型弹窗 -->
	<u-modal 
		:show="showDeviceOpen" 
		title="新增设备类型" 
		@confirm="handleConfirmAdd" 
		@cancel="handleCancel" 
		show-cancel-button
		mask-close-able
	  >
		<view>
			<u-form :model="deviceForm" ref="uForm">
				<u-form-item label="设备类型">
					<view style="padding: 8px 6px; border: 1px solid #dadbde; border-radius: 4px; font-size: 15px;">
						<view class="test-scan">
							<view v-if="!deviceForm.deviceTypeId" @click="showOpen = true">请选择设备类型</view>
							<view v-else @click="showOpen = true">{{deviceType}}</view>
							<!-- <u-picker 
								:show="showOpen" 
								@confirm="deviceTypeChange" 
								keyName="label" 
								:columns="typeList" 
								@cancel="cancel"
							>
							</u-picker> -->
							<pickerSearch v-model="showOpen" :dataSource='typeList' :pickerValues="[0]" @recload='deviceTypeChange'></pickerSearch>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="设备品牌">
					<u-input v-model="deviceForm.deviceBrand" placeholder="请输入设备品牌"/>
				</u-form-item>
				<u-form-item label="设备型号">
					<u-input v-model="deviceForm.deviceModel" placeholder="请输入设备型号"/>
				</u-form-item>
				<u-form-item label="临时照片">
					<view>
						<u-upload 
							:fileList="fileList1" 
							@afterRead="afterRead" 
							@delete="deletePic" 
							name="1" 
							:maxCount="1">
						</u-upload>
					</view>
				</u-form-item>
			</u-form>
			<image :src="photo" :key="index" 
				@click="viewPhoto(photo)" />
		</view>
	</u-modal>
  </view>
</template>

<script>
import request from "@/utils/request.js";
import login from "../../../../store/modules/login";
import pickerSearch from '@/compoments/pickerSearch.vue'

export default {
  components: {pickerSearch},
  data() {
    return {
	    searchValue: '', // 搜索值
	    showOpen: false, //类型选择弹窗
	    typeList:[], //类型
	    deviceType: null, // 展示的类型
	    typeIndex : 0,
	    updateCountOpen: false, //修改容器码数量
	    countForm: {}, // 具体数量型号表单
	    countForm1: {
		  countIncrease: 0,
		  countDecrease: 0,
	    },
        deviceList: [], // 设备列表
	    workOrderId: null, // 存储 workId 的变量
	    showDeviceOpen: false, //新增设备弹窗
	    deviceForm: {
		  deviceTypeId: null,
		  deviceBrand: null,
		  deviceModel: null,
		  // deviceSpecs: [],
	    }, //新增设备的值
		BaseUrl: "",
	    formattedDevices: [], // 筛选后的数组
	    list: [], //搜索用的数组
		fileList1: [],
		requestParams: {
			deviceModel: '',
			pageNum: 1,
			pageSize: 10,
		},
    };
  },
  onLoad(options) {
  	uni.showLoading({
  		title: '正在加载中'
  	})
	this.BaseUrl = getApp().globalData.baseURL;
  	this.getDevice();
	this.getListType()
  	uni.hideLoading()
  },
  onReachBottom() {
  	this.requestParams.pageNum = this.requestParams.pageNum - 0 + 1;
  	this.getDevice()
  },
  watch: {
  	'requestParams.deviceModel'(newVal, oldVal) {
  		this.changeSelect(newVal);
  	}
  },
  methods: {
	  // 筛选数据
	formatDevice() {
		this.formattedDevices = [];
		this.deviceList.map(item =>{
			const { deviceType, deviceBrand, deviceModel, deviceSpecs, deviceTypeId, deviceModelId, ifOnlyOne, count, unit } = item;
			const specsArray = JSON.parse(deviceSpecs || "[]");
			const specsString = specsArray.map(spec => spec[2]).join('/');
			const formattedValue = {
			    name: `${deviceType}/${deviceBrand}/${deviceModel}/${specsString}`,
			    deviceModelId: deviceModelId,
				ifOnlyOne: ifOnlyOne,
				count:count || '',
				unit: unit || '',
				deviceBrand: deviceBrand || '',
				deviceType: deviceType || '',
				deviceModel:deviceModel ||'',
				deviceTypeId: deviceTypeId || '',
				deviceSpecs:deviceSpecs
			};
			this.formattedDevices.push(formattedValue)
			this.list = this.formattedDevices;
		})
	},
	// 模糊搜索
	async searchChange(e) {
		if (e === '') {
		  this.list = this.formattedDevices;
		} else {
		  this.list = this.formattedDevices.filter(item => item.name && item.name.includes(e));
		}
		// this.reset();
	},
	clearSearch() { //清空搜索内容
		this.searchValue = ''
		this.list = this.formattedDevices
	},
	formatDeviceSpecs(specs) {
	    const specs1 = JSON.parse(specs || "[]");
	      if (specs1 && specs1.length > 0) {
		  // 将数组中的第三个元素取出，然后用 '/' 连接
		  const formattedSpecs = specs1.map(spec1 => spec1[2]).join('/');
		  return formattedSpecs;
	     } else {
		  return ''; // 或者显示的默认文本
	    }
	},
	// 新增图片
	async afterRead(event) {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file)
		let fileListLen = this[`fileList${event.name}`].length
		lists.forEach((item) => {
			this[`fileList${event.name}`].push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})
		for (let i = 0; i < lists.length; i++) {
			const result = await this.uploadFilePromise(lists[i].url, event.name)
			let item = this[`fileList${event.name}`][fileListLen]
			this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: result
			}))
			fileListLen++
		}
	},
	uploadFilePromise(url, name) {
		return new Promise((resolve, reject) => {
			uni.$u.http.upload(`${this.BaseUrl}system/oss/upload`, {
				params: {},
				/* 会加在url上 */
				// #ifdef APP-PLUS || H5
				files: [], // 需要上传的文件列表。使用 files 时，filePath 和 name 不生效。App、H5（ 2.6.15+）
				// #endif
				filePath: url, // 要上传文件资源的路径。
				// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
				custom: {
					auth: true
				}, // 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
				name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
				// #ifdef H5 || APP-PLUS
				timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
				// #endif
				header: {
					Authorization: uni.getStorageSync("token")
				},
				/* 会与全局header合并，如有同名属性，局部覆盖全局 */
				formData: {}, // HTTP 请求中其他额外的 form data
				// 返回当前请求的task, options。请勿在此处修改options。非必填
				getTask: (task, options) => {},
			}).then((res) => {
				// console.log(res);
				if (name == 1) {
					this.deviceForm.tempImageUrl = res.data.data.url.replace("blob:", "")	
				}
				resolve(res.data.data.url)
				// 返回的res.data 已经进行JSON.parse
			}).catch(err => {
	
			})
		})
	},
	// 删除图片
	deletePic(event) {
		this[`fileList${event.name}`].splice(event.index, 1)
	},
	// 存储图片
	checkImages(imageForms) {
		for (let dataElement of imageForms) {
			switch (dataElement.mediaType) {
				case "1": 
					if (dataElement.fileUrl !== null) {
						this.fileList1.push({
							type: "image",
							url: dataElement.fileUrl,
							status: "success",
							name: "",
							message: "",
							thumb: "",
							size: 60489
						})
					}
				default:
					continue;
			}
		}
	},
	// 新增设备类型
	handleAddDevice() {
		this.showDeviceOpen = true
	},
	// 新增设备
	handleConfirmAdd() {
		// this.deviceForm.deviceSpecs = JSON.stringify(this.moreForms)
		this.deviceForm.deviceSpecs = "[]"
		if (this.deviceForm.deviceTypeId === null) {
			uni.showToast({
				title:"请选择设备类型",
				icon:'none'
			})
			return
		}
		if (this.deviceForm.deviceBrand === null) {
			uni.showToast({
				title:"请选择设备品牌",
				icon:'none'
			})
			return
		}
		if (this.deviceForm.deviceModel === null) {
			uni.showToast({
				title:"请选择设备型号",
				icon:'none'
			})
			return
		}
		this.deviceForm.temp = true
		request({
			url: "system/modelLibrary",
			method: 'post',
			data: this.deviceForm
		}).then(res => {
			uni.showToast({
				title: '新增设备成功'
			})
			this.reset()
			this.getDevice()
			this.showDeviceOpen = false
		})
	},
	// 重置
	reset() {
	   this.deviceForm = {
		   deviceTypeId: null,
		   deviceBrand: null,
		   deviceModel: null,
	   }
	   this.deviceForm.tempImageUrl = ''
	   this.fileList1 = []
	},
	// 取消新增设备弹窗
	handleCancel() {
		this.showDeviceOpen = false
		// this.updateCountOpen = false
	},
	// 类型选择
	deviceTypeChange(item) {
		// console.log("1", e)
		this.deviceForm.deviceTypeId = item.id
		this.deviceType = item.name
		// this.setSelect(e.value[0].id)
		this.cancel()
	},
	
	// 筛选设备类型
	getListType() {
		request({
			url: "system/type/list",
			method: 'get',
			data: {
				disabled: "0"
			}
		}).then(res => {
			this.typeList = res.data.map(item => {
			    return {
			      name: item.code,
			      id: item.id
			    };
			});
			// this.typeList = [this.typeList];
		})
	},
	// 取消选择设备
	cancel() {
		this.showOpen = false
	},
	// 确定数据
	handleConfirm(item) {
		let pages = getCurrentPages() // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
		let prevPage = pages[pages.length - 2] //上一页页面实例
		uni.navigateBack({
			delta:1,
			success:() => {
			prevPage.$vm.otherFun(item) // 给上一页绑定方法otherFun,传参地址id
			}
		})
	},
	// 设备列表
    getDevice() {
      request({
        method: "GET",
        url: "system/modelLibrary/list",
		data: this.requestParams
      }).then((res) => {
		this.requestParams.pageNum -= (!res.rows);
        if (this.deviceList.length < res.total) {
          this.deviceList = this.deviceList.concat(res.rows);
		  this.formatDevice()
        }
      });
    },
	// 搜索功能
	changeSelect(item) {
		uni.showLoading({
			title: "正在加载中"
		})
		this.requestParams.deviceModel = item + '';
		this.requestParams.pageNum = 1;
		this.deviceList.length = 0;
		this.getDevice();
		uni.hideLoading()
	}
  },
};
</script>

<style lang="scss" scoped>
	.content {
		background: rgb(244, 249, 254);
		.header {
			position: sticky;
			top: 0;
			z-index: 999;
			display: flex;
			align-items: center;
			overflow: hidden;
			background:#f4f9fe;
			box-shadow:0px 3px 10px rgba(0, 124, 233, 0.16);
			margin-bottom: 10upx;
			/deep/ .u-search__content {
				background-color: #ffffff !important;
			}
			/deep/ .u-search__content__input {
				background-color: #ffffff !important;
			}
		}
		
		.main {
			margin-bottom: 100px;
			.main_body {
				background-color: rgb(226, 241, 255);
				margin: 20upx;
				border-radius: 2%;
				border:1px solid;
				border-color:rgba(0, 124, 233, 0.4);
				.title {
					border-bottom:1px solid;
					border-color:rgb(140, 196, 246);
					padding: 20upx;
					.main_body_view {
						margin: 10upx;
					}
							
					.main_body_view_title {
						
						margin-bottom: 10upx;
					}
				}
				.main_content {
					padding: 20upx;
					background-color: #ffffff;
				}
				
				.button {
					position: absolute;
					right: 100upx;
					width: 40rpx;
				}
				.footer{
					height:30px;
					background-color: #ffffff;
					border-bottom-left-radius: 15upx;
					border-bottom-right-radius: 15upx;
				}
			}
		}	
		.tabbar {
			position: sticky;
			bottom: 30upx;
			z-index: 999;
		}
	}
</style>
